import { invoke } from '@tauri-apps/api/tauri';

export interface File {
    file_name: string;
    file_data: Uint8Array;
}

export interface Filter {
    name: string;
    extensions: string[];
}

// 请求读取文件
export async function readFile(multi: boolean, filterName: string = "", extensions: string[] = []): Promise<File[]> {
    const cmd = 'plugin:min_app_fs|read_file';
    const request = {
        multi,
        filterName,
        extensions,
    };
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    const res = await invoke<File[]>(cmd, request);
    for (const item of res) {
        item.file_data = Uint8Array.from(item.file_data);
    }
    return res;
}

// 请求写文件
export async function writeFile(fileName: string, fileData: Uint8Array): Promise<void> {
    const cmd = 'plugin:min_app_fs|write_file';
    const request = {
        fileName,
        fileData: Array.from(fileData),
    };
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
    return invoke<void>(cmd, request);
}

// 获取文件或目录
export async function openDialog(title: string, dir: boolean, saveName: string = "", filters: Filter[] = []): Promise<string> {
    const cmd = 'plugin:min_app_fs|open_dialog';
    const request = {
        title,
        dir,
        filters,
        saveName,
    }
    console.log(`%c${cmd}`, 'color:#0f0;', request);
    return invoke<string>(cmd, request);
}